package com.ironman.compute.consumer;

import com.ironman.common.params.HeadingParam;
import com.ironman.common.util.AccuracyUtil;
import com.ironman.event.properties.SysTrainingProperties;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mica.mqtt.core.client.MqttClient;
import org.noear.snack.ONode;

import java.util.function.Consumer;

@Slf4j
public class HeadingConsumer extends BaseConsumer implements Consumer<ONode> {

    private Double preHeading = null;

    private final HeadingParam headingParam;

    public HeadingConsumer(HeadingParam headingParam, SysTrainingProperties sysTrainingProperties, MqttClient mqttClient) {
        super(sysTrainingProperties, mqttClient);
        this.headingParam = headingParam;
    }

    @Override
    public void accept(ONode data) {
        doAccept("heading", data, (topic, dataJson, published) -> log.info("{} {} \n{}", topic, published, dataJson));
    }

    @Override
    public boolean threshold(ONode data) {
        double heading = data.select("heading").getDouble();

        if (preHeading == null) {
            getCounter().incrementAndGet();
            preHeading = heading;
            data.set("tt", "t");
            return true;
        }

        Integer headingThreshold = headingParam.getHeadingThreshold();
        double diff = Math.abs(heading - preHeading);
        if (diff > headingThreshold) {
            getCounter().set(0);
            log.info("航向触发对比阈值:{} 当前:{} 前一个:{} 相差:{} ", headingThreshold, heading, preHeading, diff);
            preHeading = heading;
            data.set("tt", "t");
            return true;
        }

        Integer countThreshold = headingParam.getCountThreshold();
        if (getCounter().incrementAndGet() >= countThreshold) {
            getCounter().set(0);
            log.info("航向触发数量阈值:{} ", countThreshold);
            preHeading = heading;
            data.set("tt", "c");
            return true;
        }
        return false;
    }

    @Override
    public void precision(ONode data) {
        double headingT = data.select("headingT").getDouble();
        double headingM = data.select("headingM").getDouble();
        data.set("headingT", AccuracyUtil.downDirectionInteger(headingT));
        data.set("headingM", AccuracyUtil.downDirectionInteger(headingM));
        data.set("headingT", 90);
        data.set("headingM", 90);
    }
}
